package com.sp2p.service;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.shove.Convert;
import com.shove.base.BaseService;
import com.shove.data.DataException;
import com.shove.data.DataSet;
import com.shove.data.dao.MySQL;
import com.shove.util.BeanMapUtils;
import com.shove.vo.PageBean;
import com.sp2p.constants.IConstants;
import com.sp2p.dao.GameDao;
import com.sp2p.database.Dao.Procedures;

public class GameService extends BaseService {
	public static Log log = LogFactory.getLog(GameService.class);
	private GameDao gameDao;

	public GameDao getGameDao() {
		return gameDao;
	}

	public void setGameDao(GameDao gameDao) {
		this.gameDao = gameDao;
	}

	public List<Map<String, Object>> queryLotteryGift(long activityId)
			throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = gameDao.queryLotteryGift(conn, activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return list;
	}

	public List<Map<String, Object>> queryLotteryAward(long activityId)
			throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = gameDao.queryLotteryAward(conn, activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return list;
	}

	public Map<String, String> queryLotteryUserInfo(long userid, long activityId)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryLotteryUserInfo(conn, userid, activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> queryLotteryUserInfo(String unionid,
			long activityId) throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryLotteryUserInfo(conn, unionid, activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> queryLotteryAwardById(String unionid,
			long awardId, long activityId) throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryLotteryAwardById(conn, unionid, awardId,
					activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> queryLotteryHasPlayTimes(long userid,
			long activityId) throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryLotteryHasPlayTimes(conn, userid,
					activityId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public long gameLotteryPlay(long userId, long activityId, int prize)
			throws SQLException {
		Connection conn = MySQL.getConnection();
		long returnId = -1L;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_game_lottery_play(conn, ds, outParameterValues,
					userId, activityId, prize, -1, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long updateLotteryUserChanceNum(String unionid, long activityId)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.updateLotteryUserChanceNum(conn, unionid,
					activityId);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long updateLotteryAward(long awardId, long userId) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.updateLotteryAward(conn, awardId, userId);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long updateLotteryUserHasPlayNum(String unionid, long activityId,
			int isAward) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.updateLotteryUserHasPlayNum(conn, unionid,
					activityId, isAward);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long insertLotteryAward(String unionid, long activityId,
			int giftIndex) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.insertLotteryAward(conn, unionid, activityId,
					giftIndex);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long insertLotteryUser(String unionid, long activityId, int chanceNum)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.insertLotteryUser(conn, unionid, activityId,
					chanceNum);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public Map<String, String> querySheepMWAward(String mobilePhone)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.querySheepMWAward(conn, mobilePhone);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public long updateSheepMWAwardStatus(String mobilePhone, int awardStatus)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.updateSheepMWAwardStatus(conn, mobilePhone,
					awardStatus);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long insertSheepMWAward(String mobilePhone, int awardType,
			Double awardAmount, int awardStatus) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.insertSheepMWAward(conn, mobilePhone, awardType,
					awardAmount, awardStatus);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public Map<String, String> querySpliteEnvelopeByUserId(Long userId)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.querySpliteEnvelopeByUserId(conn, userId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> querySETreeInfo(Long senvId, String mobilePhone)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.querySETreeInfo(conn, senvId, mobilePhone);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> querySETreeRemainById(Long senvId)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.querySETreeRemainById(conn, senvId);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public Map<String, String> queryEnvelopeRemainByPhone(String mobilePhone)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryEnvelopeRemainByPhone(conn, mobilePhone);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public long spliteEnvelopeToElite(long senvId, double valMoney,
			String mobilePhone) throws SQLException {
		Connection conn = MySQL.getConnection();
		long returnId = -1L;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_splite_envelope_to_elite(conn, ds, outParameterValues,
					senvId, valMoney, mobilePhone, -1, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long spliteEnvelopeToEliteNewuser(long senvId, long userId,
			String mobilePhone) throws SQLException {
		Connection conn = MySQL.getConnection();
		long returnId = -1L;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_splite_envelope_to_elite_newuser(conn, ds,
					outParameterValues, senvId, userId, mobilePhone, -1, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long spliteEnvelopeNewuser(long userId, String mobilePhone)
			throws SQLException {
		Connection conn = MySQL.getConnection();
		long returnId = -1L;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_splite_envelope_newuser(conn, ds, outParameterValues,
					userId, mobilePhone, -1, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
		return returnId;
	}

	public long insertVoucherCode(String openid, String paycode, double money,
			int codeBatch) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.insertVoucherCode(conn, openid, paycode, money,
					codeBatch);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public Map<String, String> queryVoucherCodeByOpenid(String openid)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryVoucherCodeByOpenid(conn, openid);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	public long insertGofullVoucher(long userId, String amount,
			int usableCounts, int maxUsedTimes, String productLimit,
			int voucherType, String exchangeRate, int getType) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			returnId = gameDao.insertGofullVoucher(conn, userId, amount,
					usableCounts, maxUsedTimes, productLimit, voucherType,
					exchangeRate, getType);
			if (returnId <= 0) {
				conn.rollback();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	/**
	 * @MethodName: createRedpack
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 增加红包信息
	 * @Throws:
	 */
	public long createRedpack(Long userId, BigDecimal money, int env_status,
			int env_type, int env_count, String blessing, String senvKey,
			String unionid) throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		long returnId = -1;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_create_red_pack(conn, ds, outParameterValues, userId,
					money, env_status, env_type, env_count, blessing, senvKey,
					unionid,0, "");
			ds.tables.get(0).rows.genRowsMap();
			map = BeanMapUtils.dataSetToMap(ds);
			returnId = Convert.strToLong(map.get("senvId"), -1);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	/**
	 * @MethodName: queryRedpackById
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 通过key查询红包信息
	 * @Throws:
	 */
	public Map<String, String> queryRedpackByKey(String senvKey)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryRedpackByKey(conn, senvKey);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	/**
	 * @MethodName: gainRedpack
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 领取红包
	 * @Throws:
	 */
	public long gainRedpack(Long senvId, String unionid) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_gain_red_pack(conn, ds, outParameterValues, senvId,
					unionid, 0, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	/**
	 * @MethodName: queryRedpackRecordById
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 通过senvId,unionid查询红包领取记录
	 * @Throws:
	 */
	public Map<String, String> queryRedpackRecordById(long senvId,String unionid)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryRedpackRecordById(conn, senvId, unionid);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	/**
	 * @MethodName: queryRedpackRecords
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 红包领取记录
	 * @Throws:
	 */
	public void queryRedpackRecords(String senvKey, PageBean pageBean)
			throws Exception {
		StringBuffer condition = new StringBuffer();
		condition.append(" and senv_key ='" + senvKey + "'");
		Connection conn = connectionManager.getConnection();
		try {
			dataPage(conn, pageBean, " v_t_redpack_wechat_user ",
					" id,valMoney,isMax,nickname,headimgurl,createTimeFormat ",
					"", condition.toString());

		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryGainRpStatistics
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 统计个人红包领取记录
	 * @Throws:
	 */
	public Map<String, String> queryGainRpStatistics(String unionid)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryGainRpStatistics(conn, unionid);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}

	/**
	 * @MethodName: queryGainRpDetail
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 统计个人红包领取明细
	 * @Throws:
	 */
	public void queryGainRpDetail(String unionid, PageBean pageBean)
			throws Exception {
		StringBuffer condition = new StringBuffer();
		condition.append(" and unionid ='" + unionid + "'");
		Connection conn = connectionManager.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_redpack_wechat_user ",
					" id,valMoney,isMax,shareNickname,shareHeadimgurl,createTimeFormat,senv_key ",
					" order by id DESC ", condition.toString());

		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryShareRpStatistics
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 统计个人红包发出记录
	 * @Throws:
	 */
	public Map<String, String> queryShareRpStatistics(String unionid)
			throws Exception {
		Connection conn = connectionManager.getConnection();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = gameDao.queryShareRpStatistics(conn, unionid);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return resultMap;
	}
	
	/**
	 * @MethodName: queryShareRpDetail
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 统计个人红包发出明细
	 * @Throws:
	 */
	public void queryShareRpDetail(String unionid, PageBean pageBean)
			throws Exception {
		StringBuffer condition = new StringBuffer();
		condition.append(" and unionid ='" + unionid + "'");
		Connection conn = connectionManager.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" t_red_pack ",
					" id,money,env_type,env_status,env_count,has_count,senv_key, date_format(`createTime`, '%Y-%m-%d %H:%i') AS `createTimeFormat` ",
					" order by id DESC ", condition.toString());

		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
	}
	
	/**
	 * @MethodName: gainRedpack
	 * @Param: GameService
	 * @Author: wujc
	 * @Date:
	 * @Return:
	 * @Descb: 红包充值体验金
	 * @Throws:
	 */
	public long rechargeRedpack(Long userId, String unionid) throws Exception {
		Connection conn = connectionManager.getConnection();
		long returnId = -1;
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_red_pack_to_elite(conn, ds, outParameterValues, userId,
					unionid, 0, "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}
}
